import React, { useState } from 'react'

export default function SearchInp() {
    const [isOpen, setIsOpen] = useState(false)
    const [value, setValue] = useState("")
    // 存储历史记录
    const saveInStorage = (val: string) => {
        const historyStorage = localStorage.getItem('historyStorage')
        let list;
        // 判断一下历史记录是否存在
        if (historyStorage) {
            // 已经存在就执行push
            list = JSON.parse(historyStorage);
            list.push(val)
        } else {
            // 不存在就变成数组再存储
            list = [val]
        }
        // 存储
        localStorage.setItem('historyStorage', JSON.stringify(list))
    }
    return (
        <div className='search_inp'>
            <input
                type="text"
                placeholder='探索掘金'
                onFocus={() => {
                    // 聚焦的时候 判断一下是否有历史记录 有就打开
                    setIsOpen(() => {
                        if (localStorage.getItem('historyStorage')) {
                            return true;
                        } else {
                            return false
                        }
                    })
                }}
                onBlur={() => {
                    // 失焦关闭
                    setTimeout(() => {
                        setIsOpen(false)
                    })
                }}
                value={value}
                onChange={({ target: { value } }) => {
                    // 受控组件
                    setValue(value)
                }}
                onKeyDown={({ keyCode }) => {
                    if (keyCode === 13) { // 按下回车
                        saveInStorage(value)
                    }
                }}
            />
            {isOpen ? <SearchHistory /> : ""}
        </div>
    )
}

function SearchHistory() {
    const historyStorage = localStorage.getItem('historyStorage');
    let list = historyStorage ? JSON.parse(historyStorage) : []
    const clear = () => {
        // 清空历史记录
        localStorage.removeItem('historyStorage')
        list = []
    }
    return <div className="search_history">
        <div className="top">
            <a href="#" onClick={clear}>清空历史记录</a>
            {list.map((item: any, index: number) => {
                return <div key={index}>
                    {item}
                </div>
            })}
        </div>
    </div>
}